table of contents
SYSTEMD.SERVICE(5) | systemd.service | SYSTEMD.SERVICE(5) |
NAME¶
systemd.service - Service unit configuration
SYNOPSIS¶
service.service
DESCRIPTION¶
A unit configuration file whose name ends in .service encodes information about a process controlled and supervised by systemd.
This man page lists the configuration options specific to this unit type. See systemd.unit(5) for the common options of all unit configuration files. The common configuration items are configured in the generic "[Unit]" and "[Install]" sections. The service specific configuration options are configured in the "[Service]" section.
Additional options are listed in systemd.exec(5), which define the execution environment the commands are executed in, and in systemd.kill(5), which define the way the processes of the service are terminated, and in systemd.resource-control(5), which configure resource control settings for the processes of the service.
Unless DefaultDependencies= is set to false, service units will implicitly have dependencies of type Requires= and After= on basic.target as well as dependencies of type Conflicts= and Before= on shutdown.target. These ensure that normal service units pull in basic system initialization, and are terminated cleanly prior to system shutdown. Only services involved with early boot or late system shutdown should disable this option.
If a service is requested under a certain name but no unit configuration file is found, systemd looks for a SysV init script by the same name (with the .service suffix removed) and dynamically creates a service unit from that script. This is useful for compatibility with SysV. Note that this compatibility is quite comprehensive but not 100%. For details about the incompatibilities, see the Incompatibilities with SysV[1] document.
OPTIONS¶
Service files must include a "[Service]" section, which carries information about the service and the process it supervises. A number of options that may be used in this section are shared with other unit types. These options are documented in systemd.exec(5) and systemd.kill(5). The options specific to the "[Service]" section of service units are the following:
Type=
If set to simple (the default if neither Type= nor BusName=, but ExecStart= are specified), it is expected that the process configured with ExecStart= is the main process of the service. In this mode, if the process offers functionality to other processes on the system, its communication channels should be installed before the daemon is started up (e.g. sockets set up by systemd, via socket activation), as systemd will immediately proceed starting follow-up units.
If set to forking, it is expected that the process configured with ExecStart= will call fork() as part of its start-up. The parent process is expected to exit when start-up is complete and all communication channels are set up. The child continues to run as the main daemon process. This is the behavior of traditional UNIX daemons. If this setting is used, it is recommended to also use the PIDFile= option, so that systemd can identify the main process of the daemon. systemd will proceed with starting follow-up units as soon as the parent process exits.
Behavior of oneshot is similar to simple; however, it is expected that the process has to exit before systemd starts follow-up units. RemainAfterExit= is particularly useful for this type of service. This is the implied default if neither Type= or ExecStart= are specified.
Behavior of dbus is similar to simple; however, it is expected that the daemon acquires a name on the D-Bus bus, as configured by BusName=. systemd will proceed with starting follow-up units after the D-Bus bus name has been acquired. Service units with this option configured implicitly gain dependencies on the dbus.socket unit. This type is the default if BusName= is specified.
Behavior of notify is similar to simple; however, it is expected that the daemon sends a notification message via sd_notify(3) or an equivalent call when it has finished starting up. systemd will proceed with starting follow-up units after this notification message has been sent. If this option is used, NotifyAccess= (see below) should be set to open access to the notification socket provided by systemd. If NotifyAccess= is not set, it will be implicitly set to main. Note that currently Type=notify will not work if used in combination with PrivateNetwork=yes.
Behavior of idle is very similar to simple; however, actual execution of the service binary is delayed until all jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console.
RemainAfterExit=
GuessMainPID=
PIDFile=
BusName=
BusPolicy=
The value of this directive is comprised of two parts; the bus name, and a verb to specify to granted access, which is one of see, talk, or own. talk implies see, and own implies both talk and see. If multiple access levels are specified for the same bus name, the most powerful one takes effect.
Examples:
BusPolicy=org.freedesktop.systemd1 talk
BusPolicy=org.foo.bar see
This option is only available on kdbus enabled systems.
ExecStart=
When Type is not oneshot, only one command may and must be given. When Type=oneshot is used, zero or more commands may be specified. This can be specified by providing multiple command lines in the same directive, or alternatively, this directive may be specified more than once with the same effect. If the empty string is assigned to this option, the list of commands to start is reset, prior assignments of this option will have no effect. If no ExecStart= is specified, then the service must have RemainAfterExit=yes set.
For each of the specified commands, the first argument must be an absolute path to an executable. Optionally, if this file name is prefixed with "@", the second token will be passed as "argv[0]" to the executed process, followed by the further arguments specified. If the absolute filename is prefixed with "-", an exit code of the command normally considered a failure (i.e. non-zero exit status or abnormal exit due to signal) is ignored and considered success. If both "-" and "@" are used, they can appear in either order.
If more than one command is specified, the commands are invoked sequentially in the order they appear in the unit file. If one of the commands fails (and is not prefixed with "-"), other lines are not executed, and the unit is considered failed.
Unless Type=forking is set, the process started via this command line will be considered the main process of the daemon.
ExecStartPre=, ExecStartPost=
If any of those commands (not prefixed with "-") fail, the rest are not executed and the unit is considered failed.
Note that ExecStartPre= may not be used to start long-running processes. All processes forked off by processes invoked via ExecStartPre= will be killed before the next service process is run.
ExecReload=
One additional, special environment variable is set: if known, $MAINPID is set to the main process of the daemon, and may be used for command lines like the following:
/bin/kill -HUP $MAINPID
Note however that reloading a daemon by sending a signal (as with the example line above) is usually not a good choice, because this is an asynchronous operation and hence not suitable to order reloads of multiple services against each other. It is strongly recommended to set ExecReload= to a command that not only triggers a configuration reload of the daemon, but also synchronously waits for it to complete.
ExecStop=
ExecStopPost=
RestartSec=
TimeoutStartSec=
TimeoutStopSec=
TimeoutSec=
WatchdogSec=
Restart=
Takes one of no, on-success, on-failure, on-abnormal, on-watchdog, on-abort, or always. If set to no (the default), the service will not be restarted. If set to on-success, it will be restarted only when the service process exits cleanly. In this context, a clean exit means an exit code of 0, or one of the signals SIGHUP, SIGINT, SIGTERM or SIGPIPE, and additionally, exit statuses and signals specified in SuccessExitStatus=. If set to on-failure, the service will be restarted when the process exits with a non-zero exit code, is terminated by a signal (including on core dump, but excluding the aforementiond four signals), when an operation (such as service reload) times out, and when the configured watchdog timeout is triggered. If set to on-abnormal, the service will be restarted when the process is terminated by a signal (including on core dump, excluding the aforementioned four signals), when an operation times out, or when the watchdog timeout is triggered. If set to on-abort, the service will be restarted only if the service process exits due to an uncaught signal not specified as a clean exit status. If set to on-watchdog, the service will be restarted only if the watchdog timeout for the service expires. If set to always, the service will be restarted regardless of whether it exited cleanly or not, got terminated abnormally by a signal, or hit a timeout.
Table 1. Exit causes and the effect of the Restart= settings on them
Restart settings/Exit causes | no | always | on-success | on-failure | on-abnormal | on-abort | on-watchdog |
Clean exit code or signal | X | X | |||||
Unclean exit code | X | X | |||||
Unclean signal | X | X | X | X | |||
Timeout | X | X | X | ||||
Watchdog | X | X | X | X |
As exceptions to the setting above the service will not be
restarted if the exit code or signal is specified in
RestartPreventExitStatus= (see below). Also, the services will always
be restarted if the exit code or signal is specified in
RestartForceExitStatus= (see below).
Setting this to on-failure is the recommended choice for long-running services, in order to increase reliability by attempting automatic recovery from errors. For services that shall be able to terminate on their own choice (and avoid immediate restarting), on-abnormal is an alternative choice.
SuccessExitStatus=
SuccessExitStatus=1 2 8
SIGKILL
ensures that exit codes 1, 2, 8 and the termination signal SIGKILL are considered clean service terminations.
Note that if a process has a signal handler installed and exits by calling _exit(2) in response to a signal, the information about the signal is lost. Programs should instead perform cleanup and kill themselves with the same signal instead. See Proper handling of SIGINT/SIGQUIT — How to be a proper program[3].
This option may appear more than once, in which case the list of successful exit statuses is merged. If the empty string is assigned to this option, the list is reset, all prior assignments of this option will have no effect.
RestartPreventExitStatus=
RestartPreventExitStatus=1 6
SIGABRT
ensures that exit codes 1 and 6 and the termination signal SIGABRT will not result in automatic service restarting. This option may appear more than once, in which case the list of restart-preventing statuses is merged. If the empty string is assigned to this option, the list is reset and all prior assignments of this option will have no effect.
RestartForceExitStatus=
PermissionsStartOnly=
RootDirectoryStartOnly=
NonBlocking=
NotifyAccess=
Sockets=
Note that the same socket file descriptors may be passed to multiple processes simultaneously. Also note that a different service may be activated on incoming socket traffic than the one which is ultimately configured to inherit the socket file descriptors. Or in other words: the Service= setting of .socket units does not have to match the inverse of the Sockets= setting of the .service it refers to.
This option may appear more than once, in which case the list of socket units is merged. If the empty string is assigned to this option, the list of sockets is reset, and all prior uses of this setting will have no effect.
StartLimitInterval=, StartLimitBurst=
StartLimitAction=
FailureAction=
RebootArgument=
FileDescriptorStoreMax=
Check systemd.exec(5) and systemd.kill(5) for more settings.
COMMAND LINES¶
This section describes command line parsing and variable and specifier substitions for ExecStart=, ExecStartPre=, ExecStartPost=, ExecReload=, ExecStop=, and ExecStopPost= options.
Multiple command lines may be concatenated in a single directive by separating them with semicolons (these semicolons must be passed as separate words). Lone semicolons may be escaped as "\;".
Each command line is split on whitespace, with the first item being the command to execute, and the subsequent items being the arguments. Double quotes ("...") and single quotes ('...') may be used, in which case everything until the next matching quote becomes part of the same argument. C-style escapes are also supported, see table below. Quotes themselves are removed after parsing and escape sequences substituted. In addition, a trailing backslash ("\") may be used to merge lines.
This syntax is intended to be very similar to shell syntax, but only the meta-characters and expansions described in the following paragraphs are understood. Specifically, redirection using "<", "<<", ">", and ">>", pipes using "|", running programs in the background using "&", and other elements of shell syntax are not supported.
The command to execute must an absolute path name. It may contain spaces, but control characters are not allowed.
The command line accepts "%" specifiers as described in systemd.unit(5). Note that the first argument of the command line (i.e. the program to execute) may not include specifiers.
Basic environment variable substitution is supported. Use "${FOO}" as part of a word, or as a word of its own, on the command line, in which case it will be replaced by the value of the environment variable including all whitespace it contains, resulting in a single argument. Use "$FOO" as a separate word on the command line, in which case it will be replaced by the value of the environment variable split at whitespace resulting in zero or more arguments. For this type of expansion, quotes and respected when splitting into words, and afterwards removed.
Example:
Environment="ONE=one" 'TWO=two two' ExecStart=/bin/echo $ONE $TWO ${TWO}
This will execute /bin/echo with four arguments: "one", "two", "two", and "two two".
Example:
Environment=ONE='one' "TWO='two two' too" THREE= ExecStart=/bin/echo ${ONE} ${TWO} ${THREE} ExecStart=/bin/echo $ONE $TWO $THREE
This results in echo being called twice, the first time with arguments "'one'", "'two two' too", "", and the second time with arguments "one", "two two", "too".
To pass a literal dollar sign, use "$$". Variables whose value is not known at expansion time are treated as empty strings. Note that the first argument (i.e. the program to execute) may not be a variable.
Variables to be used in this fashion may be defined through Environment= and EnvironmentFile=. In addition, variables listed in the section "Environment variables in spawned processes" in systemd.exec(5), which are considered "static configuration", may be used (this includes e.g. $USER, but not $TERM).
Note that shell command lines are not directly supported. If shell command lines are to be used, they need to be passed explicitly to a shell implementation of some kind. Example:
ExecStart=/bin/sh -c 'dmesg | tac'
Example:
ExecStart=/bin/echo one ; /bin/echo "two two"
This will execute /bin/echo two times, each time with one argument: "one" and "two two", respectively. Because two commands are specified, Type=oneshot must be used.
Example:
ExecStart=/bin/echo / >/dev/null & \; \ /bin/ls
This will execute /bin/echo with five arguments: "/", ">/dev/null", "&", ";", and "/bin/ls".
Table 2. C escapes supported in command lines and environment variables
Literal | Actual value |
"\a" | bell |
"\b" | backspace |
"\f" | form feed |
"\n" | newline |
"\r" | carriage return |
"\t" | tab |
"\v" | vertical tab |
"\\" | backslash |
"\"" | double quotation mark |
"\'" | single quotation mark |
"\s" | space |
"\xxx" | character number xx in hexadecimal encoding |
"\nnn" | character number nnn in octal encoding |
EXAMPLES¶
Example 1. Simple service
The following unit file creates a service that will execute /usr/sbin/foo-daemon. Since no Type= is specified, the default Type=simple will be assumed. systemd will assume the unit to be started immediately after the program has begun executing.
[Unit] Description=Foo [Service] ExecStart=/usr/sbin/foo-daemon [Install] WantedBy=multi-user.target
Note that systemd assumes here that the process started by systemd will continue running until the service terminates. If the program daemonizes itself (i.e. forks), please use Type=forking instead.
Since no ExecStop= was specified, systemd will send SIGTERM to all processes started from this service, and after a timeout also SIGKILL. This behavior can be modified, see systemd.kill(5) for details.
Note that this unit type does not include any type of notification when a service has completed initialization. For this, you should use other unit types, such as Type=notify if the service understands systemd's notification protocol, Type=forking if the service can background itself or Type=dbus if the unit acquires a DBus name once initialization is complete. See below.
Example 2. Oneshot service
Sometimes units should just execute an action without keeping active processes, such as a filesystem check or a cleanup action on boot. For this, Type=oneshot exists. Units of this type will wait until the process specified terminates and then fall back to being inactive. The following unit will perform a clenaup action:
[Unit] Description=Cleanup old Foo data [Service] Type=oneshot ExecStart=/usr/sbin/foo-cleanup [Install] WantedBy=multi-user.target
Note that systemd will consider the unit to be in the state 'starting' until the program has terminated, so ordered dependencies will wait for the program to finish before starting themselves. The unit will revert to the 'inactive' state after the execution is done, never reaching the 'active' state. That means another request to start the unit will perform the action again.
Type=oneshot are the only service units that may have more than one ExecStart= specified. They will be executed in order until either they are all successful or one of them fails.
Example 3. Stoppable oneshot service
Similarly to the oneshot services, there are sometimes units that need to execute a program to set up something and then execute another to shut it down, but no process remains active while they are considered 'started'. Network configuration can sometimes fall into this category. Another use case is if a oneshot service shall not be executed a each time when they are pulled in as a dependency, but only the first time.
For this, systemd knows the setting RemainAfterExit=yes, which causes systemd to consider the unit to be active if the start action exited successfully. This directive can be used with all types, but is most useful with Type=oneshot and Type=simple. With Type=oneshot systemd waits until the start action has completed before it considers the unit to be active, so dependencies start only after the start action has succeeded. With Type=simple dependencies will start immediately after the start action has been dispatched. The following unit provides an example for a simple static firewall.
[Unit] Description=Simple firewall [Service] Type=oneshot RemainAfterExit=yes ExecStart=/usr/local/sbin/simple-firewall-start ExecStop=/usr/local/sbin/simple-firewall-stop [Install] WantedBy=multi-user.target
Since the unit is considered to be running after the start action has exited, invoking systemctl start on that unit again will cause no action to be taken.
Example 4. Traditional forking services
Many traditional daemons/services background (i.e. fork, daemonize) themselves when starting. Set Type=forking in the service's unit file to support this mode of operation. systemd will consider the service to be in the process of initialization while the original program is still running. Once it exits successfully and at least a process remains (and RemainAfterExit=no), the service is considered started.
Often a traditional daemon only consists of one process. Therefore, if only one process is left after the original process terminates, systemd will consider that process the main process of the service. In that case, the $MAINPID variable will be available in ExecReload=, ExecStop=, etc.
In case more than one process remains, systemd will be unable to determine the main process, so it will not assume there is one. In that case, $MAINPID will not expand to anything. However, if the process decides to write a traditional PID file, systemd will be able to read the main PID from there. Please set PIDFile= accordingly. Note that the daemon should write that file before finishing with its initialization, otherwise systemd might try to read the file before it exists.
The following example shows a simple daemon that forks and just starts one process in the background:
[Unit] Description=Some simple daemon [Service] Type=forking ExecStart=/usr/sbin/my-simple-daemon -d [Install] WantedBy=multi-user.target
Please see systemd.kill(5) for details on how you can influence the way systemd terminates the service.
Example 5. DBus services
For services that acquire a name on the DBus system bus, use Type=dbus and set BusName= accordingly. The service should not fork (daemonize). systemd will consider the service to be initialized once the name has been acquired on the system bus. The following example shows a typical DBus service:
[Unit] Description=Simple DBus service [Service] Type=dbus BusName=org.example.simple-dbus-service ExecStart=/usr/sbin/simple-dbus-service [Install] WantedBy=multi-user.target
For bus-activatable services, don't include a "[Install]" section in the systemd service file, but use the SystemdService= option in the corresponding DBus service file, for example (/usr/share/dbus-1/system-services/org.example.simple-dbus-service.service):
[D-BUS Service] Name=org.example.simple-dbus-service Exec=/usr/sbin/simple-dbus-service User=root SystemdService=simple-dbus-service.service
Please see systemd.kill(5) for details on how you can influence the way systemd terminates the service.
Example 6. Services that notify systemd about their initialization
Type=simple services are really easy to write, but have the major disadvantage of systemd not being able to tell when initialization of the given service is complete. For this reason, systemd supports a simple notification protocol that allows daemons to make systemd aware that they are done initializing. Use Type=notify for this. A typical service file for such a daemon would look like this:
[Unit] Description=Simple notifying service [Service] Type=notify ExecStart=/usr/sbin/simple-notifying-service [Install] WantedBy=multi-user.target
Note that the daemon has to support systemd's notification protocol, else systemd will think the service hasn't started yet and kill it after a timeout. For an example of how to update daemons to support this protocol transparently, take a look at sd_notify(3). systemd will consider the unit to be in the 'starting' state until a readiness notification has arrived.
Please see systemd.kill(5) for details on how you can influence the way systemd terminates the service.
SEE ALSO¶
systemd(1), systemctl(1), systemd.unit(5), systemd.exec(5), systemd.resource-control(5), systemd.kill(5), systemd.directives(7)
NOTES¶
- 1.
- Incompatibilities with SysV
- 2.
- kdbus
- 3.
- Proper handling of SIGINT/SIGQUIT — How to be a proper program
systemd 219 |